import React from 'react';
import {base, toast, promptBox} from 'nc-lightapp-front';
import deepCopy from "../../../../hrpub/common/utils/deep-copy";

const {NCCheckbox} = base;

export default class TableAction {
    constructor(comp) {
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
    }

    getTableData = async (code) => {
        const {props, action} = this.comp;
        const {editTable, meta, dispatch, main} = props;
        const {orgValue, selectKey, handleItem, businessInfo, orignalTemplate} = main;
        // if (!orgValue || !orgValue.refpk) return;
        dispatch({
            type: 'main/getConfig',
            payload: {
                pk_org: businessInfo.groupId,
                infoset_code: code,
                isqrypsndoc: 'N'
            }
        })
            .then(async (res) => {
                // action.tabAct.tabChange('entry');
                await props.dispatch({
                    type: 'main/update',
                    payload: {
                        approveMap: res.data.approveMap,
                        disEditMap: res.data.disEditMap,
                        gridMap: res.data.gridMap
                    }
                });
                editTable.setTableData('appconfgrid', res.data.gridMap[selectKey].appconfgrid);
                //const template = meta.getMeta();
                const template = deepCopy(orignalTemplate)
                if (!template['appconfgrid']) {
                    return;
                }
                const entry_approval = template['appconfgrid'].items.find(item => item.attrcode === 'entryHead')
                    .children.find(item => item.attrcode === 'entry_approval');
                if (entry_approval) {
                    entry_approval.visible = handleItem.infosetcode === 'bd_psndoc';
                    meta.setMeta(template);
                }
                action.tabAct.tabChange(main.tabKey);
            });
    };

    edit = async () => {
        const {props, action} = this.comp;
        const {dispatch, editTable, syncTree} = props;
        editTable.setStatus('appconfgrid', 'edit');
        this.resetHeadAndCell();
        await dispatch({
            type: 'main/update',
            payload: {
                isEdit: true
            }
        });
        syncTree.setNodeDisable('authorList', true);
        action.btnAct.updateButtonStatus();
    };

    isHeadEditable = (tableData, key) => {
        const {props: {main: {disEditMap, selectKey}}} = this.comp;
        let flag = true;
        switch (key) {
            case 'entry_card_show_edit':
                flag = disEditMap[selectKey] || !tableData.find(item => !item.values['entry_card_show_edit'].value);
                break;
            case 'entry_approval':
                flag = tableData.find(item => !item.values['entry_card_show_edit'].value);
                break;
            case 'entry_not_null':
                flag = disEditMap[selectKey] || tableData.find(item => !item.values['entry_card_show_edit'].value);
                break;
            case 'entry_card_show_notedit':
                flag = !tableData.find(item => !item.values['entry_card_show_notedit'].value);
                break;
            case 'entry_card_notshow':
                flag = !tableData.find(item => !item.values['entry_card_notshow'].value);
                break;
            case 'unentry_card_show_edit':
                flag = disEditMap[selectKey] || !tableData.find(item => !item.values['unentry_card_show_edit'].value);
                break;
            case 'unentry_not_null':
                flag = disEditMap[selectKey] || tableData.find(item => !item.values['unentry_card_show_edit'].value);
                break;
            case 'unentry_card_show_notedit':
                flag = !tableData.find(item => !item.values['unentry_card_show_notedit'].value);
                break;
            case 'unentry_card_notshow':
                flag = !tableData.find(item => !item.values['unentry_card_notshow'].value);
                break;
            case 'manager_card_notshow':
                flag = false;
                break;
        }
        return flag;
    };

    isHeadChecked = (tableData, key) => {
        return !tableData.find(item => !item.values[key].value);
    };

    onHeadChange = (isChecked, tableData, key, headItem) => {
        const {props} = this.comp;
        const {editTable, meta} = props;
        const {checkKeys, unCheckKeys} = this.getUnCheckAndCheckKeys(key, isChecked);
        tableData.forEach((row, index) => {
            checkKeys.forEach(checkKey => {
                editTable.setValByKeyAndIndex('appconfgrid', index, checkKey, {
                    value: isChecked
                });
            });
            unCheckKeys.forEach(unCheckKey => {
                editTable.setValByKeyAndIndex('appconfgrid', index, unCheckKey, {
                    value: !isChecked
                });
            });
        });
        this.resetHeadAndCell();
    };

    isCellEditable = (values, key) => {
        const {props: {main: {disEditMap, selectKey}}} = this.comp;
        let flag = true;
        switch (key) {
            case 'entry_card_show_edit':
                flag = !disEditMap[selectKey] && !values['entry_card_show_edit'].value;
                break;
            case 'entry_approval':
                flag = values['entry_card_show_edit'].value;
                break;
            case 'entry_not_null':
                flag = !disEditMap[selectKey] && values['entry_card_show_edit'].value;
                break;
            case 'entry_card_show_notedit':
                flag = !values['entry_card_show_notedit'].value;
                break;
            case 'entry_card_notshow':
                flag = !values['entry_card_notshow'].value;
                break;
            case 'entry_list_show':
                flag = !values['entry_card_notshow'].value;
                break;
            case 'unentry_card_show_edit':
                flag = !disEditMap[selectKey] && !values['unentry_card_show_edit'].value;
                break;
            case 'unentry_not_null':
                flag = !disEditMap[selectKey] && values['unentry_card_show_edit'].value;
                break;
            case 'unentry_card_show_notedit':
                flag = !values['unentry_card_show_notedit'].value;
                break;
            case 'unentry_card_notshow':
                flag = !values['unentry_card_notshow'].value;
                break;
            case 'unentry_list_show':
                flag = !values['unentry_card_notshow'].value;
                break;
            case 'manager_list_show':
                flag = !values['manager_card_notshow'].value;
                break;
        }
        return flag;
    };

    getUnCheckAndCheckKeys = (handleKey, isChecked) => {
        let keyMap = {checkKeys: [], unCheckKeys: []};
        switch (handleKey) {
            case 'entry_card_show_edit':
                keyMap = {
                    checkKeys: ['entry_card_show_edit'],
                    unCheckKeys: ['entry_card_show_notedit', 'entry_card_notshow']
                };
                break;
            case 'entry_approval':
                keyMap = {
                    checkKeys: ['entry_approval'],
                    unCheckKeys: []
                };
                break;
            case 'entry_not_null':
                keyMap = {
                    checkKeys: ['entry_not_null'],
                    unCheckKeys: []
                };
                break;
            case 'entry_card_show_notedit':
                keyMap = {
                    checkKeys: ['entry_card_show_notedit'],
                    unCheckKeys: ['entry_card_show_edit', 'entry_approval', 'entry_not_null', 'entry_card_notshow']
                };
                break;
            case 'entry_card_notshow':
                keyMap = {
                    checkKeys: ['entry_card_notshow'],
                    unCheckKeys: ['entry_card_show_edit', 'entry_approval', 'entry_not_null', 'entry_card_show_notedit', 'entry_list_show']
                };
                break;
            case 'unentry_card_show_edit':
                keyMap = {
                    checkKeys: ['unentry_card_show_edit'],
                    unCheckKeys: ['unentry_card_show_notedit', 'unentry_card_notshow']
                };
                break;
            case 'unentry_not_null':
                keyMap = {
                    checkKeys: ['unentry_not_null'],
                    unCheckKeys: []
                };
                break;
            case 'unentry_card_show_notedit':
                keyMap = {
                    checkKeys: ['unentry_card_show_notedit'],
                    unCheckKeys: ['unentry_card_show_edit', 'unentry_not_null', 'unentry_card_notshow']
                };
                break;
            case 'unentry_card_notshow':
                keyMap = {
                    checkKeys: ['unentry_card_notshow'],
                    unCheckKeys: ['unentry_card_show_edit', 'unentry_not_null', 'unentry_card_show_notedit', 'unentry_list_show']
                };
                break;
            case 'manager_card_notshow':
                keyMap = {
                    checkKeys: ['manager_card_notshow'],
                    unCheckKeys: isChecked ? ['manager_list_show'] : []
                };
                break;
            default:
                break;
        }
        return keyMap;
    };

    resetHeadAndCell = (record) => {
        const {props} = this.comp;
        const {editTable, meta} = props;
        const template = meta.getMeta();
        const tableData = editTable.getAllRows('appconfgrid');
        const allHead = ['entryHead', 'unentryHead', 'managerHead'];
        template['appconfgrid'].items.forEach(item => {
            if (allHead.includes(item.attrcode)) {
                item.children.forEach(child => {
                    if (!child.text) child.text = child.label;
                    child.label = <div>
                        <span style={{display: 'inline-block'}}>
                            <NCCheckbox
                                disabled={this.isHeadEditable(tableData, child.attrcode)}
                                checked={this.isHeadChecked(tableData, child.attrcode)}
                                onChange={(isChecked) => this.onHeadChange(isChecked, tableData, child.attrcode, item)}
                            />
                        </span>
                        <span>{child.text}</span>
                    </div>
                })
            }
        });
        meta.setMeta(template);
        editTable.setStatus('appconfgrid', 'edit');
        const handleField = ["entry_card_show_edit", "entry_approval", "entry_not_null",
            "entry_card_show_notedit", "entry_card_notshow", "entry_list_show",
            "unentry_card_show_edit", "unentry_not_null", "unentry_card_show_notedit",
            "unentry_card_notshow", "unentry_list_show", "manager_card_notshow",
            "manager_list_show"];
        if (record) {
            let editData = [];
            let tempObj = {};
            handleField.forEach(key => {
                tempObj[key] = !this.isCellEditable(record.values, key)
            });
            editData.push({
                rowid: record.rowid,
                keys: tempObj
            });
            editTable.setEditableKeyEdit('appconfgrid', editData);
        } else {
            /*tableData.forEach(row => {
                handleField.forEach(key => {
                    editTable.setEditableRowKeyByRowId('appconfgrid', row.rowid, key, this.isCellEditable(row.values, key));
                });
            });*/
            let editData = [];
            tableData.forEach((row, index) => {
                let tempObj = {};
                handleField.forEach(key => {
                    tempObj[key] = !this.isCellEditable(row.values, key)
                });
                editData.push({
                    index,
                    rowid: row.rowid,
                    keys: tempObj
                })
            });
            editTable.setEditableKeyEdit('appconfgrid', editData);
        }
    };

    cancel = () => {
        const {props, action} = this.comp;
        const {meta, dispatch, editTable, syncTree, main} = props;
        const {handleItem, language} = main;
        promptBox({
            color: 'info',
            title: language['gx6008-000239'],//国际化处理：取消保存
            content: language['gx6008-000240'],//国际化处理：是否放弃保存
            beSureBtnClick: async () => {
                const allHead = ['entryHead', 'unentryHead', 'managerHead'];
                const template = meta.getMeta();
                template['appconfgrid'].items.forEach(item => {
                    if (allHead.includes(item.attrcode)) {
                        item.children.forEach(child => {
                            if (!child.text) child.text = child.label;
                            child.label = child.text;
                        })
                    }
                });
                meta.setMeta(template);
                editTable.cancelEdit('appconfgrid');
                await dispatch({
                    type: 'main/update',
                    payload: {
                        isEdit: false
                    }
                });
                syncTree.setNodeDisable('authorList', false);
                action.btnAct.updateButtonStatus();
                this.getTableData(handleItem.infosetcode);
            }
        })
    };

    tableAfterEdit = (props, moduleId, key, value, changedrows, index, record) => {
        const {editTable} = props;
        const {checkKeys, unCheckKeys} = this.getUnCheckAndCheckKeys(key, value);
        checkKeys.forEach(checkKey => {
            editTable.setValByKeyAndIndex('appconfgrid', index, checkKey, {
                value: value
            });
        });
        unCheckKeys.forEach(unCheckKey => {
            editTable.setValByKeyAndIndex('appconfgrid', index, unCheckKey, {
                value: !value
            });
        });
        this.resetHeadAndCell(record);
    };

    changeApp = (value) => {
        const {props} = this.comp;
        const {dispatch, main} = props;
        const {approveMap, selectKey} = main;
        approveMap[selectKey] = value ? 'Y' : 'N';
        dispatch({
            type: 'main/update',
            payload: {
                approveMap
            }
        });
    };

    beforeSave = () => {
        const {props: {main: {language}}} = this.comp;
        promptBox({
            color: 'info',
            title: language['gx6008-000237'],//国际化处理： 确认保存
            content: language['gx6008-000238'],//国际化处理： 是否要覆盖已有的权限配置
            beSureBtnClick: () => {
                this.save();
            }
        });
    };

    save = async () => {
        const {props, action} = this.comp;
        const {dispatch, editTable, main, meta, syncTree} = props;
        const {selectKey, approveMap, orgValue, handleItem, language, businessInfo} = main;
        const tableData = editTable.getAllData('appconfgrid');
        let postData = {
            gridMap: JSON.stringify({[selectKey]: JSON.stringify({appconfgrid: tableData})}),
            pk_org: businessInfo.groupId,
            approveMap
        };

        let res = await dispatch({
            type: 'main/saveConfig',
            payload: postData
        });

        if (res.success) {
            toast({
                color: 'success',
                content: language['gx6008-000052']
            });
            const allHead = ['entryHead', 'unentryHead', 'managerHead'];
            const template = meta.getMeta();
            template['appconfgrid'].items.forEach(item => {
                if (allHead.includes(item.attrcode)) {
                    item.children.forEach(child => {
                        if (!child.text) child.text = child.label;
                        child.label = child.text;
                    })
                }
            });
            meta.setMeta(template);
            editTable.setStatus('appconfgrid', 'browse');
            await dispatch({
                type: 'main/update',
                payload: {
                    isEdit: false
                }
            });
            syncTree.setNodeDisable('authorList', false);
            action.btnAct.updateButtonStatus();
            this.getTableData(handleItem.infosetcode);
        }
    }
}